package hip.util;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;


/**
 * 根据properties中配置的路径把jar和配置文件加载到classpath中。
 */
public final class ExtClassLoader {

    /**
     * URLClassLoader的addURL方法
     */
    private static Method addURL = initAddMethod();

    private static URLClassLoader classloader = (URLClassLoader) ExtClassLoader.class.getClassLoader();


    /**
     * 初始化addUrl 方法.
     *
     * @return 可访问addUrl方法的Method对象
     */
    private static Method initAddMethod() {
        try {
            Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
            add.setAccessible(true);
            return add;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 加载jar classpath。
     *
     * @throws Exception
     */
    public static void loadClasspath(List<String> files) throws Exception {
        for (String f : files) {
            loadClasspath(f);
        }

    }

    public static List<String> loadClasspath(String filepath) throws Exception {
        //	jars=new ArrayList<String>();
        File file = new File(filepath);
        List<String> jars = new ArrayList<String>();
        loopFiles(file, jars);
        return jars;
    }

    @SuppressWarnings("rawtypes")
    public static Object loadClass(String name) throws Exception {
        Class nClass = Class.forName(name);
        return nClass.newInstance();
    }

    public static void loadAJar(String file) throws Exception {
        addURL(new File(file));
    }

    public static void loadAJar(File file) throws Exception {
        addURL(file);
    }

    // 循环遍历目录，找出所有的jar包。
    private static void loopFiles(File file, List<String> jars) throws Exception {
        if (file.isDirectory()) {
            File[] tmps = file.listFiles();
            for (File tmp : tmps) {
                loopFiles(tmp, jars);
            }
        } else {
            if (file.getAbsolutePath().endsWith(".jar") || file.getAbsolutePath().endsWith(".zip")) {
                jars.add(file.getName());
                addURL(file);
            }
        }
    }

    //通过filepath加载文件到classpath。
    private static void addURL(File file) throws Exception {
        addURL.invoke(classloader, new Object[]{file.toURI().toURL()});
    }
}

